package com.LeeCode;

/**
 * 替换子串得到平衡字符串
 */

public class Code1234 {
    public static void main(String[] args) {
        String s = "QQWE";
        System.out.println(new Code1234().balancedString(s));
    }

    public int balancedString(String s) {
        char[] chars = s.toCharArray();
        int[] cnt = new int[26];
        for (char c : chars) {
            cnt[c - 'A']++;
        }
        int n = s.length(), m = n / 4;
        if (cnt['Q' - 'A'] == m && cnt['W' - 'A'] == m && cnt['E' - 'A'] == m && cnt['R' - 'A'] == m) {
            return 0;
        }

        int ans = n, left = 0;
        for (int right = 0; right < chars.length; right++) {
            cnt[chars[right] - 'A']--;

            while (cnt['Q' - 'A'] <= m && cnt['W' - 'A'] <= m && cnt['E' - 'A'] <= m && cnt['R' - 'A'] <= m) {
                ans = Math.min(ans, right - left + 1);
                cnt[chars[left] - 'A']++;
                left++;
            }
        }

        return ans;
    }
}
